package com.movie.app.controller;

import java.net.http.HttpHeaders;
import java.util.List;
import java.util.Map;

import com.movie.app.model.Admin;
import com.movie.app.model.Article;
import com.movie.app.model.ResponseCode;
import com.movie.app.utils.Jwt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/article/")
public class ArticleController{
	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private Jwt jwt;

	@PostMapping("/")
	@ResponseBody
	public ResponseCode add(@RequestBody Article art, @RequestHeader Map<String, String> headers){
		String jwtString;
		ResponseCode rcode = new ResponseCode();
		try {
			jwtString = headers.get("jwt");
		} catch (Exception e) {
			rcode.setCode(0);
			return rcode;
		}
		Jwt jwt = new Jwt();
		String id = jwt.verifyToken(jwtString);

		Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Admin admin  = mongoTemplate.findOne(query, Admin.class);
		if(id=="null" || admin==null){
			rcode.setCode(0);
			rcode.setContent("no auth");
			return rcode;
		}

		ArticleFilter filter = new ArticleFilter();
		rcode = filter.addValid(art);

		if (rcode.getCode()==0) {
			return rcode;
		}
		
		Article article = new Article();
		
		article.setTitle(art.getTitle());
	    article.setAuthor(art.getAuthor());
	    article.setUrl(art.getUrl());
	    mongoTemplate.save(article);

		return rcode;
	}
}
